<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Amqp\Producers\CrowdInviteProducer;
use App\CustHub\Amqp\Producers\SendRecordProducers;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\RobotApplyConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Dto\InviteStaticDayDto;
use App\CustHub\Dto\InviteStaticRobotDto;
use App\CustHub\Dto\SmartTagStatsDto;
use App\CustHub\Mapper\ChContactWhiteMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChSmartTagMapper;
use App\CustHub\Mapper\CrowdInviteMapper;

use App\CustHub\Mapper\SmartAnswerMapper;
use App\CustHub\Model\ChCrowdInvite;
use App\CustHub\Model\ChCrowdInviteLog;
use App\CustHub\Model\ChSmartAnswer;
use App\CustHub\Model\ChSmartAnswerQuestion;
use App\CustHub\Model\ChSmartAnswerRecord;
use App\CustHub\Model\ChSmartAnswerReplyQuestion;
use App\Exception\BusinessException;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\RobotApiService;
use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use Hyperf\Di\Annotation\Inject;
use Mine\MineCollection;
use function Hyperf\Collection\data_get;
use function Hyperf\Coroutine\co;

class SmartAnswerService extends AbstractService
{
    #[Inject]
    protected ChRobotApplyService $applyService;

    #[Inject]
    protected ChSendConfigService $sendConfigService;

    #[Inject]
    protected ChCrowSendingService $chCrowSendingService;

    #[Inject]
    protected ChContactWhiteMapper $contactWhiteMapper;

    #[Inject]
    protected ChRobotService $chRobotService;

    #[Inject]
    protected CommonService $commonService ;

    /**
     * @var string
     * 对象图片数量缓存key
     */
    protected $imagesTimesKey="ch@smartanswer:times";

    public function __construct(SmartAnswerMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 触发智能应答序号问题
     */
    public function smartQuestion($params)
    {
        $uid=data_get($params,'uid');
        $robotUserId=data_get($params,'user_id');
        $robotId=data_get($params,'robot_id');
        $content=data_get($params,'content');
        $sender=data_get($params,'sender');
        $isRoom=data_get($params,'is_room');
        $tid=$sender;
        if($isRoom)$tid=$params['from_room_id'];
        if(empty($robotId)) return false;

        if($content['msg_type']!='text'){
            return false;
        }
        //查找最新的
        $record=ChSmartAnswerRecord::query()->where('reply_type',1)->where('robot_id',$robotId)->where('sender',$sender)->where('is_question_list',1)->latest()->first();
        if(empty($record)){
            return false;
        }
        $schemeList=$this->mapper->getSchemeList($robotId);
        if(empty($schemeList)) return false;
        $lastId=$record['id'];
        $list=ChSmartAnswerReplyQuestion::query()->with('question')->where('reply_id',$lastId)->orderBy('sort','asc')->get()->toArray();
        $currentQuestion=null;
        foreach ($list as $item){
            if($item['sort']==$content['content']){
                $currentQuestion=$item;
                break;
            }
        }
        if(empty($currentQuestion)) return false;
        if(!in_array($currentQuestion['question']['answer_id'],array_column($schemeList,'id'))){
            return true;
        }
        if($currentQuestion['question']['answer_type']==1){
            $reply=$currentQuestion['question']['content'];
        }else{
            $reply=[$currentQuestion['question']['content'][rand(0,count($currentQuestion['question']['content'])-1)]];
        }
        if($reply){
            $this->chCrowSendingService->sendRecord([$tid],0,0,[$robotId],SendConfigConstants::SMART_ANSWER,0,0,time(),$reply,0,$params['is_room'],true,false);
            //保存回复记录
            ChSmartAnswerRecord::saveRecord($robotId,$sender,$tid,1,$reply,$currentQuestion['question_id']);
            return true;
        }
        return false;
    }


    /**
     * 触发智能应答
     */
    public function smartAnswer($params)
    {
        logger()->info('智能应答检测开始...');
        logger()->info(json_encode($params,256));
        $robotUserId=data_get($params,'user_id');
        $robotId=data_get($params,'robot_id');
        $content=data_get($params,'content');
        $at_list=data_get($params,'at_list');
        if(redis()->get('new_user:'.$robotId."_".$params['sender'])){
            logger()->info('新用户');
            return false;
        }
        if(empty($robotId) || empty($content)) return false;
        $robotInfo=$this->chRobotService->mapper->findById($robotId);
        $uid=$robotInfo->uid;
        $mainUid=$robotInfo->main_uid;
        //同一个群里多个机器人互相之间不触发恢复
        if($this->chRobotService->mapper->model::query()->where([
            'user_id'=>$params['sender'],
            'main_uid'=>$mainUid,
        ])->where('id','<>',$robotId)->first()){
           return false;
        }
        //查找机器人方案
        //$ids=$this->applyService->getApplyTargetOnlineIds(RobotApplyConstants::SMART_ANSWER,$robotId);
        //if($ids->isEmpty()) return false;
        //获取机器人配置
        $config=$this->sendConfigService->getConfig(SendConfigConstants::SMART_ANSWER,$uid,$robotId,true);
        //$list=ChSmartAnswer::query()->whereIn('id',$ids)->where('status',1)->get()->toArray();
        $list=$this->mapper->getSchemeList($robotId);
        if(empty($list)) return false;
        $satisfyList=[];
        //取出满足条件的方案
        $nowTime=time();
        foreach ($list as $item){
            //判断是否在回复时间段
            if($item['answer_times_type']!=1){
                // 新增的按周几和时间段判断
                if (!empty($item['answer_time_config']) && !$this->isInWeeklyTimeRange($item['answer_time_config'], $nowTime)) {
                    continue;
                }
            }
            //判断是否是目标用户
            if($item['answer_type']==1){
                //1按客户
                if($params['is_room']==1){
                    if(empty($item['crowd_ids']) || !in_array($params['from_room_id'],$item['crowd_ids'])){
                        continue;
                    }
                }else{
                    if(empty($item['crowd_ids']) || !in_array($params['sender'],$item['custom_ids'])){
                        continue;
                    }
                }
            }elseif($item['answer_type']==2){
                //2按条件
                $custom_conf=$item['condition_conf']['custom_conf'];
                $custom_conf['conf']=!empty($custom_conf['conf'])?[$custom_conf['conf']]:[];
                $crowd_conf=$item['condition_conf']['crowd_conf'];
                $crowd_conf['conf']=!empty($crowd_conf['conf'])?[$crowd_conf['conf']]:[];
                if(empty($crowd_conf['type'])) $crowd_conf['type']=1;
                if(empty($custom_conf['type'])) $custom_conf['type']=1;

                if($params['is_room']==1){
                    if($crowd_conf['type'] != 1){
                        $crowdIds=$this ->chCrowSendingService->getCrowdList($robotId,$item['uid'],$item['main_uid'],$crowd_conf);
                        if(empty($crowdIds) || !in_array($params['from_room_id'],$crowdIds)){
                            continue;
                        }
                    }
                }else{
                    if($custom_conf['type'] != 1){
                        $customIds=$this ->chCrowSendingService->getContactList($robotId,$item['uid'],$custom_conf);
                        if(empty($customIds) || !in_array($params['sender'],$customIds)){
                            continue;
                        }
                    }
                }
            }else{
                continue;
            }

            //排除对象
            //1.排除发送者是系统用户
            if($item['is_answer_other_online'] && $this->chRobotService->isSystemSender($params['sender'])){
                continue;
            }
            //2.白名单用户
            if($item['is_answer_white'] && $this->contactWhiteMapper->checkContactExists($params['sender'],$mainUid)){
                continue;
            }
            $satisfyList[]=$item;
        }
        //判断是否需要自动打标签 todo
        if(empty($satisfyList)) return false;
        //触发回复
        if($config['trigger'] ==1){
             //全部触发
        }elseif($config['trigger'] ==2){
            //随机触发一个
            $satisfyList=[$satisfyList[mt_rand(0, count($satisfyList) - 1)]];
        }
        //logger()->info('智能应答触发方案-机器人-'.$robotId."触发源内容:".json_encode($content,256),$satisfyList);
        $this->triggerReply($satisfyList,$params['sender'],$robotId,$robotUserId,$params['is_room'],$content,$at_list,$params['from_room_id']);

    }

    /**
     * 触发回复
     */
    public function triggerReply($satisfyList,$sender,$robotId,$robotUserId,$isRoom,$content,$at_list=null,$room_id=0)
    {
        $tid=$sender;
        if($isRoom)$tid=$room_id;
        foreach ($satisfyList as $item){
            logger()->info('关键词检测开始...');
            $isTrigger=false;
            $delay=rand($item['answer_limit_min'],$item['answer_limit_max']);
            $startTime=time();
            $isSendNow=true;
            if($item['open_keyword']){
                $triggerKeyword=true;
                //关键词应答
                $keyword_conf=$item['keyword_conf']['guzze'];
                while (true){
                    //群里面必须@自己
                    if($isRoom && $keyword_conf[0]['checked']){
                        if(empty($at_list)){
                            logger()->info('没有@自己...');
                            $triggerKeyword=false;
                            break;
                        }
                        $adUsers = array_column($at_list,'user_id');
                        if(!in_array($robotUserId,$adUsers)){
                            logger()->info('没有@自己...'.'机器人userid:'.$robotUserId.'@的用户id:'.json_encode($adUsers));
                            $triggerKeyword=false;
                            break;
                        }
                    }
                    //自己可触发关键词
                    if(!$keyword_conf[3]['checked'] && $robotUserId==$sender){
                        logger()->info('自己不可触发关键词...');
                        $triggerKeyword=false;
                        break;
                    }
                    $questionList=ChSmartAnswerQuestion::query()->where('answer_id',$item['id']) -> orderBy('sort','desc')->get()->toArray();
                    //var_dump('关键词应答内容');
                    //var_dump($content);
                    $flag=$this->triggerKeyword($item,$keyword_conf,$questionList,$sender,$tid,$robotId,$content,$item['keyword_conf']['guide'],$startTime,$isRoom,$isSendNow,$delay);
                    if($flag){
                        logger()->info('触发关键词回复成功');
                        $isTrigger=true;
                    }
                    break;
                }

            }
            if($item['open_image'] && !$isTrigger){
                logger()->info('未触发回复开始图片回复检测...');
                $triggerImages=true;
                while (true){
                    var_dump('图文应答');
                    if(empty($item['image_conf']['content'])){
                        $triggerImages=false;
                        break;
                    }
                    $image_conf=$item['image_conf']['guzze'];
                    if($content['msg_type']!='image'){
                        $triggerImages=false;
                        break;
                    }

                    if($image_conf[2]['checked'] && $this->triggerRepeatByTime($image_conf[2]['value'],2,$robotId,$sender)){
                        logger()->info($image_conf[2]['value'].'时间内已触发图片回复');
                        $triggerImages=false;
                        break;
                    }
                    //增加图片数量
                    $this->incImageTimes($robotId,$sender);
                    //判断图片数量
                    if($image_conf[0]['checked']){
                        $imageTimes=$image_conf[0]['value'];
                        $nowTimes=$this->getImageTimes($robotId,$sender);
                        if($nowTimes<$imageTimes){
                            logger()->info('已经发送图片数量'.$nowTimes.'设置的图片数量'.$imageTimes.'未达到图片数量限制');
                            $triggerImages=false;
                            break;
                        }
                    }
                    //判断单位时间内的图片合并
                    if($image_conf[1]['checked']){
                        $lastSendTime=$this->getLastReplyTime(2,$robotId,$sender);

                        if($lastSendTime && (strtotime($lastSendTime) > (time()-$image_conf[1]['value']))){
                            //60秒之内已经发过了就不发了
                            logger()->info('最后发送图片时间'.$lastSendTime.'设置的多少秒图片合并回复'.$image_conf[1]['value'].'未达到单位时间图片合并限制');
                            $triggerImages=false;
                            break;
                        }
                        //60秒之内没发过检测60秒内有没有图片
                        $nowTimes=$this->getImageTimes($robotId,$sender);
                        if(!$nowTimes){
                            logger()->info('单位时间内没有任何图片发送');
                            $triggerImages=false;
                            break;
                        }
                    }
                    break;
                }
                if($triggerImages ){
                    logger()->info('触发图片回复...');
                    //发送图片
                    $content=$item['image_conf']['content'];
                    $this->reomveImageTimes($robotId,$sender);
                    $isTrigger=true;
                    //触发回复
                    $this->chCrowSendingService->sendRecord([$tid],$item['uid'],$item['main_uid'],[$robotId],SendConfigConstants::SMART_ANSWER,$item['id'],0,$startTime,$content,$delay,$isRoom,$isSendNow,false);
                    //保存回复记录
                    $record=ChSmartAnswerRecord::saveRecord($robotId,$sender,$tid,2,$content);
                }
            }
            if($item['open_default'] && !$isTrigger){
                logger()->info('未触发回复开始默认回复检测...');
                $triggerDefault=true;
                $default_conf=$item['default_conf']['guzze'];
                while(true){
                    if(empty($item['default_conf']['content'])){
                        $triggerDefault =false;
                        break;
                    }
                    //群里面必须@自己
                    if($isRoom && $default_conf[0]['checked']){
                        if(empty($at_list)){
                            logger()->info('没有@自己...');
                            $triggerDefault=false;
                            break;
                        }
                        $adUsers = array_column($at_list,'user_id');
                        if(!in_array($robotUserId,$adUsers)){
                            logger()->info('没有@自己...'.'机器人userid:'.$robotUserId.'@的用户id:'.json_encode($adUsers));
                            $triggerDefault=false;
                            break;
                        }
                    }
                    if($default_conf[2]['checked'] && $this->triggerRepeatByTime($default_conf[2]['value'],3,$robotId,$sender)){
                        logger()->info($default_conf[2]['value'].'时间内已触发默认回复');
                        $triggerDefault=false;
                        break;
                    }
                    if($triggerDefault){
                        //发送
                        $content=$item['default_conf']['content'];
                        //回复消息时@对方
                        if($default_conf[1]['checked']){
                            $newContent[]=[
                                'subtype'=>1,
                                'text'=>$sender,
                            ];
                            $AltContent=[[
                                "msg_type"=>"mixed_text",
                                "content"=>$newContent
                            ]];
                        }
                        $isTrigger=true;
                        logger()->info('默认回复触发');
                        //触发回复
                        if(!empty($item['default_conf']['delay'])){
                            logger()->info('默认回复延迟'.$item['default_conf']['delay']);
                            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                                classname: SmartAnswerService::class,
                                method: 'delaySend',
                                data:[
                                    'robot_id' => $robotId,
                                    'sender' => $sender,
                                    'tid' => $tid,
                                    'uid' => $item['uid'],
                                    'main_uid' => $item['main_uid'],
                                    'robotId' => $robotId,
                                    'taskId' => $item['id'],
                                    'startTime' => $startTime,
                                    'content' => $content,
                                    'altContent' => !empty($AltContent)?$AltContent:[],
                                    'delay' => $delay,
                                    'isRoom' => $isRoom,
                                    'defaultDelay' => $item['default_conf']['delay'],
                                ]
                            )),(int) $item['default_conf']['delay']);
                        }else{
                            logger()->info('默认回复直接发送');
                            !empty($AltContent) && $this->chCrowSendingService->sendRecord([$tid],$item['uid'],$item['main_uid'],[$robotId],SendConfigConstants::SMART_ANSWER,$item['id'],0,$startTime,$AltContent,$delay,$isRoom,$isSendNow,false);
                            $this->chCrowSendingService->sendRecord([$tid],$item['uid'],$item['main_uid'],[$robotId],SendConfigConstants::SMART_ANSWER,$item['id'],0,$startTime,$content,$delay,$isRoom,$isSendNow,false);
                            //保存回复记录
                            $record=ChSmartAnswerRecord::saveRecord($robotId,$sender,$tid,3,$content);
                        }

                    }
                    break;
                }
            }
        }
    }

    public function delaySend($params)
    {
        logger()->info('延迟发送默认应答');
        //$sender,$tid,$uid,$main_uid,$robotId,$taskId,$startTime,$content,$delay,$isRoom
        $sender=$params['sender'];
        $tid=$params['tid'];
        $uid=$params['uid'];
        $main_uid=$params['main_uid'];
        $robotId=$params['robotId'];
        $taskId=$params['taskId'];
        $startTime=$params['startTime'];
        $content=$params['content'];
        $altContent=$params['altContent'];
        $delay=$params['delay'];
        $isRoom=$params['isRoom'];
        $defaultDelay=$params['defaultDelay'];
        if($this->triggerRepeatByTime($defaultDelay,[1,2,3],$robotId,$sender,0,2)){
            logger()->info('延迟时间内已经触发过默认应答'.$defaultDelay);
            return;
        }
        !empty($altContent) && $this->chCrowSendingService->sendRecord([$tid],$uid,$main_uid,[$robotId],SendConfigConstants::SMART_ANSWER,$taskId,0,$startTime,$altContent,$delay,$isRoom,true,false);
        $this->chCrowSendingService->sendRecord([$tid],$uid,$main_uid,[$robotId],SendConfigConstants::SMART_ANSWER,$taskId,0,$startTime,$content,$delay,$isRoom,true,false);
        //保存回复记录
        ChSmartAnswerRecord::saveRecord($robotId,$sender,$tid,3,$content);
    }


    public function triggerKeyword($answerInfo,$keyword_conf,$questionList,$sender,$tid,$robotId,$content,$guide,$startTime,$isRoom,$isSendNow,$delay)
    {
        $triggerQuestion=[];
        if(empty($content['msg_type'])) return false;
        if($content['msg_type']!='text' && $content['msg_type']!='mixed_text') return false;
        foreach ($questionList as $question){
            $trigger=false;
            if($content['msg_type']=='mixed_text'){
                $msgContent=$content['content'];
                foreach ($msgContent as $item){
                    if($item['type']=='text'){
                        $msgContent=$item['text'];
                        break;
                    }
                }
            }else{
                $msgContent=$content['content'];
            }

            // 更彻底的空白字符清理
            $msgContent = trim($msgContent);
            $msgContent = preg_replace('/[\s\0\x0B\p{Zs}]+/u', ' ', $msgContent);
            $msgContent = trim($msgContent);
            $msgContent = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $msgContent);
            //logger()->info('关键词:'.$msgContent);
            $keywords = $question['keyword'];
            $fuzzy_keywords = $question['fuzzy_keyword'];
            if(!empty($keywords) && in_array($msgContent,$keywords)){
                //精准触发
                logger()->info('精准触发');
                $trigger=true;
            }
            if(!$trigger && !empty($msgContent)){
                if(!empty($fuzzy_keywords)){
                    foreach ($fuzzy_keywords as $kw){
                        if(mb_strpos($kw, $msgContent) !== false){
                            //模糊触发
                            logger()->info('模糊触发'.$kw."--".$msgContent);
                            $trigger=true;
                        }
                    }
                }
            }
            if($trigger){
                $triggerQuestion[]=$question;
            }
        }
        if(empty($triggerQuestion)) return false;
        //组装回复内容
        $reply = $this->formatKeywordText($triggerQuestion,$guide,$keyword_conf[1]['checked']);
        //单位时间内不重复触发
        if($keyword_conf[4]['checked'] && $this->triggerRepeatByTime($keyword_conf[4]['value'],1,$robotId,$sender,$reply['question_id'])){
            logger()->info($keyword_conf[4]['value'].'时间内已触发问题'.$question['id']);
            return false;
        }
        //回复消息时@对方
        if($keyword_conf[2]['checked']){
            $newContent[]=[
                'subtype'=>1,
                'text'=>$sender,
            ];
            $newReply=[[
                "msg_type"=>"mixed_text",
                "content"=>$newContent
            ]];
            $altContent=$newReply;
        }

        //触发回复
        !empty($altContent) && $this->chCrowSendingService->sendRecord([$tid],$answerInfo['uid'],$answerInfo['main_uid'],[$robotId],SendConfigConstants::SMART_ANSWER,$answerInfo['id'],0,$startTime,$altContent,$delay,$isRoom,$isSendNow,false);
        $this->chCrowSendingService->sendRecord([$tid],$answerInfo['uid'],$answerInfo['main_uid'],[$robotId],SendConfigConstants::SMART_ANSWER,$answerInfo['id'],0,$startTime,$reply['reply'],$delay,$isRoom,$isSendNow,false);
        logger()->info('触发关键词回复内容',$reply);
        //保存回复记录
        $is_question_list=!empty($reply['saveData'])?1:0;
        $record=ChSmartAnswerRecord::saveRecord($robotId,$sender,$tid,1,$reply['reply'],$reply['question_id'],$is_question_list);
        if($reply['saveData']){
            foreach ($reply['saveData'] as $item){
                ChSmartAnswerReplyQuestion::saveReplyQuestion($item['question_id'],$record->id,$item['sort']);
            }
        }
        return true;
    }


    /**
     * 组装关键词回复文字
     */
    public function formatKeywordText($triggerQuestion,$guide,$withTitle=false)
    {
        if(empty($triggerQuestion)) return false;
        $saveData=[];
        if(count($triggerQuestion)==1){
            if($triggerQuestion[0]['answer_type']==1){
                $reply=$triggerQuestion[0]['content'];
            }else{
                $reply=[$triggerQuestion[0]['content'][rand(0,count($triggerQuestion[0]['content'])-1)]];
            }
            if($withTitle){
               foreach ($reply as $k=>$i){
                   $reply[$k]['content']=$triggerQuestion[0]['title']."\n".$i['content'];
               }
            }
            $question_id=$triggerQuestion[0]['id'];
        }elseif (count($triggerQuestion)>1){
            //组装序号回复
            foreach ($triggerQuestion as $key=>$question)
            {
                $guide.="\n".($key+1)."、".$question['title'];
                $saveData[]=['question_id'=>$question['id'],'sort'=>$key+1];
                if($key==0){
                    $question_id=$question['id'];
                }else{
                    $question_id.=",".$question['id'];
                }
            }
            $reply=[["msg_type"=>'text','content'=>$guide]];
        }
        $reply=$this->commonService->formatBeforeSend($reply);
        return['reply'=>$reply,'saveData'=>$saveData,'question_id'=>$question_id];
    }

    /**
     * 判断单位时间内是否已经触发过
     * @param $unitType  1-分钟 2-秒
     */
    public function triggerRepeatByTime($minute,$replyType,$robotId,$sender,$questionId=0,$unitType = 1)
    {
        if(is_array($replyType)){
            $log=ChSmartAnswerRecord::query()->whereIn('reply_type',$replyType)->where('robot_id',$robotId)->where('sender',$sender);
        }else{
            $log=ChSmartAnswerRecord::query()->where('reply_type',$replyType)->where('robot_id',$robotId)->where('sender',$sender);
        }
        if($replyType==1){
            $log->where('question_id',$questionId);
        }
        $endTime=datetime(time());
        if($unitType == 1){
            $startTime=datetime(time()-$minute*60);
        }else{
            $startTime=datetime(time()-$minute);
        }
        $log->whereBetween('created_at',[$startTime,$endTime]);
        return $log->count()>0;
    }

    /**
     * 获取最后发送时间
     */
    public function getLastReplyTime($replyType,$robotId,$sender)
    {
        $info = ChSmartAnswerRecord::query()->where('reply_type',$replyType)->where('robot_id',$robotId)->where('sender',$sender)->latest()->first()->toArray();
        return !empty($info)?$info['created_at']:false;

    }

    protected function getImageTimesKey($robotId,$sender)
    {
        return $this->imagesTimesKey.":".$robotId.":".$sender;
    }


    /**
     *获取图片已发送数量
     */
    public function getImageTimes($robotId,$sender)
    {
        $cacheKey=$this->getImageTimesKey($robotId,$sender);
        $times=redis()->get($cacheKey)?:0;
        return $times;
    }

    /**
     *增加客户图片数量
     */
    public function incImageTimes($robotId,$sender)
    {
        $cacheKey=$this->getImageTimesKey($robotId,$sender);
        $times=redis()->get($cacheKey)?:0;
        $times++;
        redis()->set($cacheKey,$times,24*3600);
    }

    /**
     *发送成功后移除数量
     */
    public function reomveImageTimes($robotId,$sender)
    {
        $cacheKey=$this->getImageTimesKey($robotId,$sender);
        redis()->del($cacheKey);
    }

    /**
     * 清除缓存
     * @param $robotId
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function clearSchemeCache($robotIds)
    {
        foreach ($robotIds as $robotId){
            $this->mapper->clearSchemeCache($robotId);
        }
    }



    /**
     * 判断当前时间是否在设置的周几和时间段范围内
     *
     * @param array $timeRangeConfig 时间段配置，格式如下：
     * [
     *   "week" => [0, 1, 2, 3, 4, 5, 6],
     *   "time_range" => [
     *     [
     *       "answer_start" => "8:00",
     *       "answer_end" => "12:00"
     *     ],
     *     [
     *       "answer_start" => "16:00",
     *       "answer_end" => "22:00"
     *     ]
     *   ]
     * ]
     * @param int $nowTime 当前时间戳
     * @return bool
     */
    protected function isInWeeklyTimeRange($timeRangeConfig, $nowTime)
    {
        // 获取当前是星期几 (0表示星期天)
        $currentWeekDay = (int)date('w', $nowTime);
        foreach ($timeRangeConfig as $config){
            if(empty($config['week'])){
                continue;
            }
            if(empty($config['time_range'])){
                continue;
            }
            // 检查今天是否在允许的星期范围内
            if (!in_array($currentWeekDay, $config['week'])) {
                continue;
            }
            // 获取当前时间 (格式: H:i)
            $currentTime = date('Hi', $nowTime);
            // 检查当前时间是否在任何允许的时间段内
            foreach ($config['time_range'] as $timeRange) {
                $startTime = trim(str_replace(':', '', $timeRange['answer_start'])); // 去除空格
                $endTime = trim(str_replace(':', '', $timeRange['answer_end']));     // 去除空格
                // 处理跨天情况 (结束时间小于开始时间)
                if ($endTime < $startTime) {
                    // 如果当前时间大于等于开始时间 或者 小于等于结束时间
                    if ($currentTime >= $startTime || $currentTime <= $endTime) {
                        return true;
                    }
                } else {
                    // 正常情况 (开始时间 <= 结束时间)
                    if ($currentTime >= $startTime && $currentTime <= $endTime) {
                        return true;
                    }
                }
            }
        };
        return false;
    }
}